package com.dotflat.fin.controller;

import com.dotflat.fin.PO.ExportPayRecordPO;
import com.dotflat.fin.PO.FinPlanOrderPO;
import com.dotflat.fin.PO.PayRecordPO;
import com.dotflat.fin.domain.FinPlanOrder;
import com.dotflat.fin.domain.PayRecord;
import com.dotflat.fin.service.FinPlanOrderService;
import com.dotflat.fin.service.PayRecordService;
import com.dotflat.fin.utils.excelUtil.ExcelUtil;
import com.dotflat.rest.controller.RestfulBaseController;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.model.StatusResponse;
import com.matt.commons.page.PagerQuery;
import com.matt.ext.aliyun.OSSProcessService;
import com.matt.foundation.dto.teach.ChildDTO;
import com.matt.foundation.utils.CopyUtils;
import com.matt.repository.base.ClienteleNativeRepository;
import com.matt.service.TeachCallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import static com.matt.foundation.constant.CommonConstant.TICKET;


/**
 * @author ：Ron
 * @date ：Created in 11/6/2020 5:07 PM
 */
@RestController
@RequestMapping("/fin/record")
@Slf4j
@Api(tags = "财务 - 支付记录")
public class PayRecordController extends RestfulBaseController<PayRecord, PayRecordService, PayRecordPO> {

    @Autowired
    public void setBaseService(PayRecordService service){
        this.baseService = service;
    }

    @Autowired
    private FinPlanOrderService orderService;

    @Autowired
    private TeachCallService teachCallService;

    @Autowired
    private ClienteleNativeRepository clienteleNativeRepository;

    @Autowired
    private OSSProcessService ossProcessService;

    @Value("${aliyun.oss.fileServerPrefix}")
    private String IMG_SERVICE_PREFIX;

    @ApiOperation(value = "增加一条记录", hidden = true)
    @Override
    public StatusResponse add(@RequestHeader(TICKET) String ticket, PayRecordPO param){
        return null;
    }

    @ApiOperation(value = "逻辑删除一个或多个对象", hidden = true)
    @Override
    public StatusResponse delete(@RequestHeader(TICKET) String ticket, String[] ids, String id ){
        return null;
    }

    @ApiOperation(value = "获取列表")
    @GetMapping("/list")
    @Override
    public StatusResponse getList(@RequestHeader(TICKET) String ticket, PayRecordPO param, PagerQuery pagerQuery){

        String classId = param.getClassId();
        String childrenName = param.getChildName();
        param.setChildName(null);
        param.setClassId(null); //需要置空，不然rest框架会自动查询这个不存在的字段，报错

        //然后根据班级id和小朋友姓名过滤
        List<ChildDTO> children = null;  //方便后面重新装配小朋友信息
        String className = null;
        if (StringUtils.isNotBlank(classId) || StringUtils.isNotBlank(childrenName)){
            //有班级id的时候，限定客户id范围
            children = teachCallService.getChildClassList(ticket, 1, childrenName, classId,null);
            if (children != null && children.size() > 0) {
                List<String> clienteleIds = children.stream().map(o->o.getCrmClienteleId()).collect(Collectors.toList());

                FinPlanOrderPO orderParam = new FinPlanOrderPO();
                BeanUtils.copyProperties(param, orderParam);
                orderParam.setPayStatus(1);//已付款
                orderParam.setClienteleIds(clienteleIds);

                StaffDTO staff = cache.getStaff(ticket);
                List<FinPlanOrder> orders = orderService.list(staff.getAreaId(), staff.getId(), orderParam);
                List<String> orderIds = orders.stream().map(FinPlanOrder::getId).collect(Collectors.toList());
                if (orderIds != null && orderIds.size() > 0){
                    param.setPayOrderIds(orderIds);
                }else {
                    return StatusResponse.success(new PageImpl<>(new ArrayList<>()));
                }
            }
        }

        StatusResponse res = super.getList(ticket, param, pagerQuery);

        Page<PayRecord> orders = (Page<PayRecord>) res.getData();

        if (orders == null || orders.getContent() == null | orders.getContent().size() == 0){
            return res;
        }

        //重新获取班级关系
        if (children == null){
            //重新获取班级关系
            List<String> clienteleIds = orders.getContent().stream().map(o-> o.getFinPlanOrder().getClienteleId()).collect(Collectors.toList());
            children = teachCallService.getChildClassList(ticket, 1, null, null, clienteleIds);
        }

        //重新装配班级信息
        if (children != null && children.size() > 0){
            List<ChildDTO> finalChildren = children;
            orders.getContent().stream().forEach(o->{
                Optional<ChildDTO> op = finalChildren.stream().filter(c->o.getFinPlanOrder().getClienteleId().equals(c.getCrmClienteleId())).findFirst();
                if (op.isPresent()){
                    ChildDTO child = op.get();
                    o.setClassName(child.getClassNames());
                }
            });
        }
        String finalClassName = className;
        List<PayRecordPO> ret = orders.getContent().stream().map(o->{
            PayRecordPO pr = new PayRecordPO();
            Double totalAmount  = Double.valueOf( o.getFinPlanOrder().getTotalAmount())/100;
            CopyUtils.copyProperties(o, pr);
            FinPlanOrderPO po = new FinPlanOrderPO();
            CopyUtils.copyProperties(o.getFinPlanOrder(), po);
            po.setTotalAmount(totalAmount);
            pr.setPayOrder(po);
            if (null != finalClassName){
                pr.setChildName(finalClassName);
            }
            return pr;
        }).collect(Collectors.toList());
        return StatusResponse.success(new PageImpl<>(ret, PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize()), orders.getTotalElements()));
//        return res;
    }

    @RequestMapping(value = "/export_list")
    @ApiOperation(value = "导出 - 支付记录", httpMethod = "GET", response = Integer.class)
    public StatusResponse clienteleSortCount(@RequestHeader String ticket, PayRecordPO param, PagerQuery pagerQuery) throws  Exception{
        pagerQuery.setPageSize(999);
        Page<PayRecordPO> page  = (Page<PayRecordPO>) getList( ticket,  param,  pagerQuery).getData();
        List<PayRecordPO> list =  page.getContent();
        List<ExportPayRecordPO> ret = list.stream().map(o->{
            ExportPayRecordPO po = new ExportPayRecordPO();
            CopyUtils.copyProperties(o,po);
            po.setPlanName(o.getPayOrder().getPlanName());
            po.setPaiedTime(o.getPayOrder().getPaiedTime());
            po.setChildName(o.getPayOrder().getChildName());
            po.setTotalAmount(o.getPayOrder().getTotalAmount());
            po.setOrderSn(o.getPayOrder().getOrderSn());
            return po;
        }).collect(Collectors.toList());
        ExcelUtil<ExportPayRecordPO> util = new ExcelUtil<ExportPayRecordPO>(ExportPayRecordPO.class);
        File outputFile = new File(util.exportExcel(ret, "参数数据") );
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());

        String uploadPath = "teach/file/children_export_excel/" + DateTime.now().toString("yyyy-MM") + "/收费记录.xlsx" ;
        String relativePath = ossProcessService.aliyunOssUpload(uploadPath, outputFile);
        String uploadedResult = IMG_SERVICE_PREFIX + relativePath;

        outputFile.deleteOnExit();
        outputFile.delete();
        return StatusResponse.success(uploadedResult);
    }
}
